package com.tongqin.distributed;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * Hello world!
 */
public class App {
    public static void main(String[] args) {

        try {
            CountDownLatch countDownLatch = new CountDownLatch(1);
            ZooKeeper zooKeeper = new ZooKeeper("172.16.233.128:2181", 4000, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    //这个是连接成功的状态
                    if(watchedEvent.getState()==Event.KeeperState.SyncConnected){
                        countDownLatch.countDown();
                    }
                }
            });
            //当前主线程的等待
            countDownLatch.await();
            System.out.println(zooKeeper.getState());//CONNECTING
            //CONNECTED 连接成功的状态

            /**
             * 打一个参数是key 路径
             * 第二个参数是值，第三个参数是权限acl，zk提供了acl的一个集合，
             * 第四个参数节点类型，是持久化还是临时节点
             * OPEN_ACL_UNSAFE:所有人都可以操作
             * CreateMode.PERSISTENT：持久化节点
             */
            zooKeeper.create("/zk-change1","0".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            Thread.sleep(1000);
            //zookeeper支持乐观锁的概念，修改前先得到节点的值
            Stat stat = new Stat();
            byte[] data = zooKeeper.getData("/zk-change1", null, stat);
            System.out.println(new String(data));

            //修改节点值
            zooKeeper.setData("/zk-change1","1".getBytes(),stat.getVersion());

            byte[] data1 = zooKeeper.getData("/zk-change1", null, stat);
            System.out.println(new String(data1));
            zooKeeper.delete("/zk-change1",stat.getVersion());
            zooKeeper.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }

    }
}
